package com.yunji.web.system;

import com.google.common.collect.Maps;
import com.yunji.common.annotation.Log;
import com.yunji.common.base.BaseController;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.enums.common.BusinessType;
import com.yunji.common.model.bo.TreeSelect;
import com.yunji.common.model.domain.SysDeptDO;
import com.yunji.common.model.domain.SysRoleDO;
import com.yunji.common.model.domain.SysUserDO;
import com.yunji.common.utils.ExcelUtil;
import com.yunji.common.utils.SecurityUtils;
import com.yunji.common.utils.StringUtils;
import com.yunji.system.context.SystemContext;
import com.yunji.system.service.ISysDeptService;
import com.yunji.system.service.ISysPostService;
import com.yunji.system.service.ISysRoleService;
import com.yunji.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
@Api(tags = "用户信息")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public Response<List<SysUserDO>> list(SysUserDO user) {
        List<SysUserDO> list = userService.selectUserList(user);
        return ResponseHelper.successWithPage(list);
    }

    @ApiOperation("导出用户信息")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserDO user) {
        List<SysUserDO> list = userService.selectUserList(user);
        ExcelUtil<SysUserDO> util = new ExcelUtil<SysUserDO>(SysUserDO.class);
        util.exportExcel(response, list, "用户数据");
    }

    @ApiOperation("导入用户信息")
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public Response<String> importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUserDO> util = new ExcelUtil<SysUserDO>(SysUserDO.class);
        List<SysUserDO> userList = util.importExcel(file.getInputStream());
        String operName = SystemContext.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return ResponseHelper.success(message);
    }


    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUserDO> util = new ExcelUtil<SysUserDO>(SysUserDO.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("根据用户编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public Response<Map<String, Object>> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        List<SysRoleDO> roles = roleService.selectRoleAll();
        Map<String, Object> map = Maps.newHashMap();
        map.put("roles", SysUserDO.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        map.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUserDO sysUser = userService.selectUserById(userId);
            map.put("data", sysUser);
            map.put("postIds", postService.selectPostListByUserId(userId));
            map.put("roleIds", sysUser.getRoles().stream().map(SysRoleDO::getRoleId).collect(Collectors.toList()));
        }
        return ResponseHelper.success(map);
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Response<Long> add(@Validated @RequestBody SysUserDO user) {
        if (!userService.checkUserNameUnique(user)) {
            return ResponseHelper.failure("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return ResponseHelper.failure("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return ResponseHelper.failure("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SystemContext.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (SystemContext.isPlate() && user.getBelongId() == null) {
            user.setBelongId(1L);
            user.setUserType("00");
        }
        Assert.isTrue(userService.insertUser(user) > 0, "新增失败");
        return ResponseHelper.success(user.getUserId());
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Response<String> edit(@Validated @RequestBody SysUserDO user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return ResponseHelper.failure("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return ResponseHelper.failure("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUserName(user.getPhonenumber());
        user.setUpdateBy(SystemContext.getUsername());
        Assert.isTrue(userService.updateUser(user) > 0, "修改失败");
        return ResponseHelper.success();
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public Response<String> remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SystemContext.getUserId())) {
            return ResponseHelper.failure("当前用户不能删除");
        }
        Assert.isTrue(userService.deleteUserByIds(userIds) > 0, "删除失败");
        return ResponseHelper.success();
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public Response<String> resetPwd(@RequestBody SysUserDO user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SystemContext.getUsername());
        Assert.isTrue(userService.resetPwd(user) > 0, "重置失败");
        return ResponseHelper.success();
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public Response<String> changeStatus(@RequestBody SysUserDO user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SystemContext.getUsername());
        Assert.isTrue(userService.updateUserStatus(user) > 0, "修改失败");
        return ResponseHelper.success();
    }

    /**
     * 根据用户编号获取授权角色
     */
    @ApiOperation("根据用户编号获取授权角色")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public Response<Map<String, Object>> authRole(@PathVariable("userId") Long userId) {
        SysUserDO user = userService.selectUserById(userId);
        List<SysRoleDO> roles = roleService.selectRolesByUserId(userId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        map.put("roles", SysUserDO.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ResponseHelper.success(map);
    }

    /**
     * 用户授权角色
     */
    @ApiOperation("用户授权角色")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public Response<String> insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return ResponseHelper.success();
    }

    /**
     * 获取部门树列表
     */
    @ApiOperation("获取部门树列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public Response<List<TreeSelect>> deptTree(SysDeptDO dept) {
        return ResponseHelper.success(deptService.selectDeptTreeList(dept));
    }
}
